import productReturnService, {
  type PageListReq,
} from "@/api/services/wms/productReturnService";
import warehouseService from "@/api/services/wms/warehouseService";
import CustomTable from "@/components/grid/CustomTable";
import TableDictTag from "@/components/grid/TableDictTag";
import { t } from "@/locales/i18n";
import {
  Button,
  Card,
  Col,
  DatePicker,
  Drawer,
  Form,
  Input,
  Row,
  Select,
  Space,
  Spin,
  Tabs,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import WmsProductReturnDetailPage, {
  type WmsProductReturnDetailHandles,
} from "./detail";
import type { WmsProductReturn } from "./entity";
import useDictionary from "@/hooks/system/useDictionary";

const { TextArea } = Input;

export default function WmsProductReturnPage() {
  const detailRef = useRef<WmsProductReturnDetailHandles>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    returnCode: undefined,
    workOrderCode: undefined,
    warehouseId: undefined,
    status: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<WmsProductReturn[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<WmsProductReturn | null>(null);
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);
  const [warehouseList, setWarehouseList] = useState<WmsWarehouse[]>([]);

  const statusOptions = useDictionary("common_order_status");

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  useEffect(() => {
    getWarehouseList();
  }, []);

  const columns: ColumnsType<WmsProductReturn> = [
    {
      title: "退料单号",
      width: 120,
      key: "returnCode",
      dataIndex: "returnCode",
    },
    {
      title: "工单号",
      width: 120,
      key: "workOrderCode",
      dataIndex: "workOrderCode",
    },
    {
      title: "退料仓库",
      width: 120,
      key: "warehouseName",
      dataIndex: "warehouseName",
    },
    {
      title: "退料日期",
      width: 120,
      key: "returnDate",
      dataIndex: "returnDate",
    },
    {
      title: "单据状态",
      width: 120,
      key: "status",
      dataIndex: "status",
      render: (_, record) => (
        <TableDictTag
          dictCode="common_order_status"
          value={record.status ?? ""}
        />
      ),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    productReturnService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 获取仓库下拉数据
  const getWarehouseList = () => {
    warehouseService
      .selectList()
      .then((res) => {
        setWarehouseList(res);
      })
      .catch((error) => {
        console.error(error);
        toast.error("加载仓库数据失败！");
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (wmsProductReturn: WmsProductReturn) => {
    setEditingData(wmsProductReturn);
    form.setFieldsValue({
      ...wmsProductReturn,
      returnDate: wmsProductReturn.returnDate
        ? dayjs(wmsProductReturn.returnDate)
        : undefined,
    });
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (wmsProductReturn: WmsProductReturn) => {
    setEditingData(wmsProductReturn);
    form.setFieldsValue({
      ...wmsProductReturn,
      returnDate: wmsProductReturn.returnDate
        ? dayjs(wmsProductReturn.returnDate)
        : undefined,
    });
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: WmsProductReturn) => {
    try {
      setSubmitLoading(true);

      //生产退料单明细
      const deleteDetailIds = detailRef.current?.getDeleteIds();
      const addDetails = detailRef.current?.getAddList();
      const updateDetails = detailRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        returnDate: values.returnDate
          ? dayjs(values.returnDate).format("YYYY-MM-DD")
          : undefined,
        deleteDetailIds: deleteDetailIds,
        addDetails: addDetails,
        updateDetails: updateDetails,
      };
      if (editingData) {
        await productReturnService.update(data);
        toast.success("更新生产退料单成功");
      } else {
        await productReturnService.add(data);
        toast.success("创建生产退料单成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await productReturnService.remove(selectedRowKeys);
      toast.success("删除生产退料单成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="returnCode" label="退料单号">
            <Input placeholder="请输入退料单号" allowClear />
          </Form.Item>
          <Form.Item name="workOrderCode" label="工单号">
            <Input placeholder="请输入工单号" allowClear />
          </Form.Item>
          <Form.Item name="warehouseId" label="退料仓库">
            <Input placeholder="请输入退料仓库" allowClear />
          </Form.Item>
          <Form.Item name="status" label="单据状态">
            <Select options={statusOptions} allowClear style={{ width: 170 }} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑生产退料单" : "新增生产退料单"}
        width={800}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button
                type="primary"
                loading={submitLoading}
                onClick={() => form.submit()}
              >
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="returnCode"
                label="退料单号"
                rules={[
                  {
                    required: true,
                    message: "请填写退料单号",
                  },
                ]}
              >
                <Input placeholder="请输入退料单号" allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="workOrderCode" label="工单号">
                <Input placeholder="请输入工单号" allowClear />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="warehouseId" label="退料仓库">
                <Select
                  options={warehouseList.map((item) => ({
                    label: item.name,
                    value: item.id,
                  }))}
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="returnDate" label="退料日期">
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="remark"
                label="备注"
                labelCol={{ span: 3 }}
                wrapperCol={{ span: 21 }}
              >
                <TextArea />
              </Form.Item>
            </Col>
          </Row>

          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1  ",
                label: "生产退料单明细",
                children: (
                  <WmsProductReturnDetailPage
                    ref={detailRef}
                    parentId={editingData?.id}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>
    </Spin>
  );
}
